#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    int candy(vector<int>& ratings) {
        priority_queue<pair<int,int>,vector<pair<int,int>>, greater<>> p_que;
        vector<int> cnt(ratings.size(), 0);
        int n = ratings.size();
        for(int i=0; i<n; ++i) p_que.push({ratings[i], i});
        
        int ans = 0;
        while(!p_que.empty()){
            auto& it = p_que.top();
            if(it.second>0 && it.first<ratings[it.second-1] && cnt[it.second]>=cnt[it.second-1]){
                cnt[it.second-1] = cnt[it.second]+1;
            }
            if(it.second<n-1 && it.first<ratings[it.second+1] && cnt[it.second]>=cnt[it.second+1]){
                cnt[it.second+1] = cnt[it.second]+1;
            }
            p_que.pop();
        }

        ans+=ratings.size();
        for(auto& it:cnt) ans+=it;
        return ans;
    }
};